package org.west.sky.experience.bigtalkdp.chapter17;

/**
 * @author: chz
 * @date: 2023/7/3
 * @description:
 */
public class Test {
    public static void main(String[] args) {
//        test1();
//        test2();
//        test3();
//        test4();
        test5();
//        test10();
    }

    /**
     * 三次获取到的都是同一个对象
     */
    private static void test1() {
        Singleton instance = Singleton.instance();
        System.out.println(instance);

        Singleton instance2 = Singleton.instance();
        System.out.println(instance2);

        Singleton instance3 = Singleton.instance();
        System.out.println(instance3);

        System.out.println(instance == instance3);
    }

    /**
     * 并发访问
     */
    private static void test2() {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                Singleton instance = Singleton.instance();
                System.out.println(instance);
            }).start();
        }
    }

    /**
     * 并发访问，并发锁保证线程安全
     */
    private static void test3() {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                Singleton instance = Singleton.instance2();
                System.out.println(instance);
            }).start();
        }
    }

    /**
     * 并发访问，并发锁保证线程安全
     */
    private static void test4() {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                Singleton instance = Singleton.instance3();
                System.out.println(instance);
            }).start();
        }
    }

    /**
     * 并发访问，并发锁保证线程安全、volatile版本
     */
    private static void test5() {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                Singleton instance = Singleton.instance4();
                System.out.println(instance);
            }).start();
        }
    }

    /**
     * 饿汉模式
     */
    private static void test10() {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                Singleton2 instance = Singleton2.instance();
                System.out.println(instance);
            }).start();
        }
    }
}
